package by.bsu.scs.util.form;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import org.apache.struts.action.Action;
import org.apache.struts.util.LabelValueBean;

import by.bsu.scs.db.dao.CourseHome;
import by.bsu.scs.db.dao.DisciplineHome;
import by.bsu.scs.db.dao.DisciplineInstructorHome;
import by.bsu.scs.db.dao.DisciplineStudentGroupHome;
import by.bsu.scs.db.dao.MessageHome;
import by.bsu.scs.db.dao.UserHome;
import by.bsu.scs.model.Course;
import by.bsu.scs.model.Discipline;
import by.bsu.scs.model.DisciplineInstructor;
import by.bsu.scs.model.DisciplineTask;
import by.bsu.scs.model.Group;
import by.bsu.scs.model.Message;
import by.bsu.scs.model.MessageAttachment;
import by.bsu.scs.model.User;
import by.bsu.scs.presentation.form.MessageForm;
/**
 * 
 * @author Svetlana Voiteh
 * @version 1.0
 *
 * Fill the elements of MessageForm
 */
public class MessageFormFiller {

	public static final int GROUP = 10;
	private MessageForm form;
	private User user;

	public MessageFormFiller(MessageForm form, User user) {
		this.form = form;
		this.user = user;
	}

	// ************ Methods for Instructors *********************

	/**
	 *  fill elements of MessageForm for instructor
	 *   
	 */
	@SuppressWarnings("unchecked")
	public void fillElementsForInstructor() {
		ArrayList<LabelValueBean> disciplineList = new ArrayList<LabelValueBean>();
		ArrayList<LabelValueBean> userList = new ArrayList<LabelValueBean>();
		ArrayList<LabelValueBean> groupList = new ArrayList<LabelValueBean>();
		ArrayList<LabelValueBean> courseList = new ArrayList<LabelValueBean>();

		/*
		 *  Fill disciplineList
		 */
		List<Discipline> discipline = (new DisciplineInstructorHome())
				.getDisciplineByInstructor(this.user);

		for (Discipline d : discipline) {
			disciplineList.add(new LabelValueBean(d.getDisciplineName(),
					(new Integer(d.getDisciplineId()).toString())));
		}
		/*
		 *  Sort disciplines
		 */
		Collections.sort(disciplineList, LabelValueBean.CASE_INSENSITIVE_ORDER);

		/*
		 *  Fill courseList
		 */
		List<Course> course = (new CourseHome()).findByExample(new Course());
		for (Course c : course) {
			courseList.add(new LabelValueBean(
					(new Integer(c.getCourseNumber())).toString(),
					(new Integer(c.getCourseId()).toString())));
		}

		/*
		 *  Fill groupList
		 */
		for (int i = 1; i <= GROUP; i++) {
			groupList.add(new LabelValueBean((new Integer(i)).toString(),
					(new Integer(i).toString())));
		}

		/*
		 *  Fill userList
		 */
		List<User> user = (new DisciplineStudentGroupHome())
				.getStudentsByInstructorId(this.user);
		for (User u : user) {
			userList.add(new LabelValueBean(u.getUserSurname() + " "
					+ u.getUserName(), (new Integer(u.getUserId()).toString())));
		}
		/*
		 *  Sort students
		 */
		Collections.sort(userList, LabelValueBean.CASE_INSENSITIVE_ORDER);

		this.form.setDisciplineList(disciplineList);
		this.form.setCourseList(courseList);
		this.form.setGroupList(groupList);
		this.form.setUserList(userList);
	}

	/**
	 * Создает новый список студентов по определенным критериям
	 */
	@SuppressWarnings("unchecked")
	public void filterStudents() {
		ArrayList<LabelValueBean> userList = new ArrayList<LabelValueBean>();
		List<User> user = null;
		if (this.form.getDisciplineId() != 0) {

			/*
			 *  Get Students By Instructor, Discipline
			 */
			if (this.form.getCourseId() == 0 && this.form.getGroupId() == 0) {
				user = (new DisciplineStudentGroupHome())
						.getStudentsByInstructorDisciplineSQL(this.user,
								new DisciplineHome().findById(this.form
										.getDisciplineId()));
			} else {
				Group group = new Group();

				/*
				 *  Get Students By Instructor, Discipline, Course
				 */
				if (this.form.getCourseId() != 0 && this.form.getGroupId() == 0) {
					group.setCourseId((new CourseHome().findById(this.form
							.getCourseId())));
					user = (new DisciplineStudentGroupHome())
							.getStudentsByInstructorDisciplineCourseSQL(
									this.user, new DisciplineHome()
											.findById(this.form
													.getDisciplineId()), group);
				}

				/*
				 *  Get Students By Instructor, Discipline, Group
				 */
				if (this.form.getCourseId() == 0 && this.form.getGroupId() != 0) {
					group.setGroupNumber(this.form.getGroupId());
					user = (new DisciplineStudentGroupHome())
							.getStudentsByInstructorDisciplineGroupSQL(
									this.user, new DisciplineHome()
											.findById(this.form
													.getDisciplineId()), group);
				}

				/*
				 *  Get Students By Instructor, Discipline, Group, Course
				 */
				if (this.form.getCourseId() != 0 && this.form.getGroupId() != 0) {
					group.setCourseId((new CourseHome().findById(this.form
							.getCourseId())));
					group.setGroupNumber(this.form.getGroupId());
					user = (new DisciplineStudentGroupHome())
							.getStudentsByInstructorDisciplineGroupCourseSQL(
									this.user, new DisciplineHome()
											.findById(this.form
													.getDisciplineId()), group);
				}
			}

			for (User u : user) {
				userList.add(new LabelValueBean(u.getUserSurname() + " "
						+ u.getUserName(), (new Integer(u.getUserId())
						.toString())));
			}
			/*
			 *  Sort user
			 */
			Collections.sort(userList, LabelValueBean.CASE_INSENSITIVE_ORDER);
		}

		this.form.getUserList().clear();
		this.form.setUserList(userList);
	}

	/**
	 * Возвращает сообщение, которое преподаватель
	 * отправляет студенту.
	 * 
	 * @return message
	 */
	public Message createMessageSendForInstructor() {
		Message messageSend = new Message();

		messageSend.setMessageDate(new Date(Calendar.getInstance()
				.getTimeInMillis()));
		messageSend.setUserFrom(this.user);
		messageSend.setIsRead(false);
		messageSend.setMessageBody(this.form.getMessage());
		messageSend.setIsVisibleReceiver(true);
		messageSend.setIsVisibleSender(true);

		/*
		 * Если это ответ на сообщение
		 */
		if (this.form.getMessageAnswer() != null) {
			messageSend.setMessageSubject(this.form.getMessageAnswer()
					.getMessageSubject());
			messageSend.setUserTo(this.form.getMessageAnswer().getUserFrom());
			messageSend.setIsFirstMessage(false);
			messageSend.setParentMessage(this.form.getMessageAnswer());
		}
		/*
		 * Если это новое сообщение
		 */
		else {
			messageSend.setMessageSubject((new DisciplineHome()).findById(
					this.form.getDisciplineId()).getDisciplineName());
			messageSend.setUserTo((new UserHome()).findById(this.form
					.getUserToId()));
			messageSend.setIsFirstMessage(true);
			messageSend.setParentMessage(null);
		}
		return messageSend;
	}

	// ************ Methods for Students *********************

	/**
	 *  fill elements of MessageForm for student
	 */
	@SuppressWarnings("unchecked")
	public void fillElementsForStudent() {
		ArrayList<LabelValueBean> userList = new ArrayList<LabelValueBean>();
		List<DisciplineInstructor> disciplineInstructor = (new DisciplineInstructorHome())
				.getDisciplineInstructorByStudentIdSQL(this.user);
		for (DisciplineInstructor d : disciplineInstructor) {
			userList.add(new LabelValueBean(d.getInstructor().getUserSurname()
					+ " " + d.getInstructor().getUserName() + "( "
					+ d.getDiscipline().getDisciplineName() + " )",
					(new Integer(d.getDisciplineInstructorId()).toString())));
		}
		/*
		 *  Sort instructors
		 */
		Collections.sort(userList, LabelValueBean.CASE_INSENSITIVE_ORDER);

		this.form.setUserList(userList);
	}

	/**
	 * Возвращает сообщение, которое студент
	 * отправляет преподавателю.
	 * 
	 * @return message
	 */
	public Message createMessageSendForStudent() {
		Message messageSend = new Message();

		messageSend.setMessageDate(new Date(Calendar.getInstance()
				.getTimeInMillis()));
		messageSend.setUserFrom(this.user);
		messageSend.setIsRead(false);
		messageSend.setMessageBody(this.form.getMessage());
		messageSend.setIsVisibleReceiver(true);
		messageSend.setIsVisibleSender(true);

		/*
		 * Если это ответ на сообщение
		 */
		if (this.form.getMessageAnswer() != null) {
			messageSend.setMessageSubject(this.form.getMessageAnswer()
					.getMessageSubject());
			messageSend.setUserTo(this.form.getMessageAnswer().getUserFrom());
			messageSend.setIsFirstMessage(false);
			messageSend.setParentMessage(this.form.getMessageAnswer());
		}
		/*
		 * Если это новое сообщение
		 */
		else {
			messageSend.setMessageSubject((new DisciplineInstructorHome())
					.findById(this.form.getUserToId()).getDiscipline()
					.getDisciplineName());
			messageSend.setUserTo((new DisciplineInstructorHome()).findById(
					this.form.getUserToId()).getInstructor());
			messageSend.setIsFirstMessage(true);
			messageSend.setParentMessage(null);
		}
		return messageSend;
	}
	
	/**
	 * Создает сообщение, которое является
	 * вопросом студента преподавателю по конкретному заданию.
	 * 
	 * @param disciplineTask
	 */
	public void createMessageQuestion(DisciplineTask disTask) {
		Message message = new Message();
		message.setMessageDate(new Date(Calendar.getInstance()
				.getTimeInMillis()));
		message.setMessageSubject(disTask.getDisciplineInstructor()
				.getDiscipline().getDisciplineName());
		message.setUserTo(disTask.getDisciplineInstructor().getInstructor());
		this.form.setUserToId(disTask.getDisciplineInstructor()
				.getDisciplineInstructorId());
		this.form.setMessage(disTask.getTask().getTaskTitle() + ": "
				+ disTask.getTask().getTaskDescription());
		this.form.setMessageQuestion(message);

	}

	// ************ Common Methods *********************

	/**
	 *  Create message attachment
	 *  
	 *  @param action
	 *  @param message
	 *  @return messageAttachment
	 */
	public MessageAttachment createMessageAttachement(Action action,
			Message message) {
		MessageAttachment mesAttachment = null;
		FileManager fileUpload = new FileManager();
		String path = fileUpload.upload(this.form.getFileAttach(), action);
		if (path != null) {
			mesAttachment = new MessageAttachment();
			mesAttachment.setFilePath(path);
			mesAttachment.setMessageId((Message) new MessageHome()
					.findByExample(message).get(0));
		}
		return mesAttachment;
	}

	/**
	 *  check existence of file upload
	 */
	public boolean isFileUploadExist() {
		boolean result = false;
		/*
		 *  if file attachment exist
		 */
		if (this.form.getFileAttach().getFileName().length() > 0) {
			result = true;
		}
		return result;
	}

	
	/**
	 *  clear all elements of MessageForm
	 */
	public void clearAll() {
		this.form.setCourseId(0);
		this.form.setDisciplineId(0);
		this.form.setUserToId(0);
		this.form.setGroupId(0);
		this.form.setMessageAnswer(null);
		this.form.setMessage(null);
		this.form.setCourseList(null);
		this.form.setDisciplineList(null);
		this.form.setGroupList(null);
		this.form.setUserList(null);
		this.form.setMessageList(null);
		this.form.setFile(null);
		this.form.setMessageQuestion(null);
	}
}
